package com.xnx3.wangmarket.plugin.innerDown.controller.admin;

import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.xnx3.wangmarket.plugin.base.controller.BasePluginController;
import com.xnx3.wangmarket.plugin.innerDown.entity.InnerDownFile;
import com.xnx3.DateUtil;
import com.xnx3.StringUtil;
import com.xnx3.j2ee.Global;
import com.xnx3.j2ee.func.AttachmentFile;
import com.xnx3.j2ee.service.SqlService;
import com.xnx3.j2ee.util.Page;
import com.xnx3.j2ee.util.Sql;
import com.xnx3.j2ee.vo.BaseVO;
import com.xnx3.wangmarket.admin.util.AliyunLog;

/**
 * 下载系统，文件管理，总管理后台使用
 * @author 管雷鸣
 */
@Controller
@RequestMapping("/plugin/innerDown/admin/file/")
public class AdminFileInnerDownPluginController extends BasePluginController{
	@Resource
	private SqlService sqlService;
	
	/**
	 * 文件列表
	 */
	@RequestMapping("/list${url.suffix}")
	public String list(HttpServletRequest request,Model model){
		if(!haveSuperAdminAuth()){
			return error(model, "无权使用");
		}
		
	    Sql sql = new Sql(request);
	    /*
	     * 设置可搜索字段。这里填写的跟user表的字段名对应。只有这里配置了的字段，才会有效。这里没有配置，则不会进行筛选
	     * 具体规则可参考： http://note.youdao.com/noteshare?id=3ccef2de6a5cda01f95f832b02e356d0&sub=D53E681BBFF04822977C7CFBF8827863
	     */
	    sql.setSearchColumn(new String[]{"name", "url", "userid=","isdelete", "suffix", "branchid="});
	    int count = sqlService.count("plugin_innerdown_file", sql.getWhere());
	    Page page = new Page(count, 30, request);
	    sql.setSelectFromAndPage("SELECT plugin_innerdown_file.*, user.nickname AS nickname FROM plugin_innerdown_file LEFT JOIN user ON plugin_innerdown_file.userid = user.id", page);
	    sql.setOrderByField(new String[]{"size","addtime"});
	    sql.setDefaultOrderBy("plugin_innerdown_file.addtime DESC");
	    List<Map<String,Object>> list = sqlService.findMapBySql(sql);
	    
	    //将展示的列表数据记录传到页面以供显示
	    model.addAttribute("list", list);
	    //将分页信息传到页面以供显示底部分页
	    model.addAttribute("page", page);
	    return "plugin/innerDown/admin/file/list";
	}
	

	/**
	 * 添加、修改文件
	 * @param id 要编辑的是哪个文件，若不传或者传0，则是添加文件
	 */
	@RequestMapping(value="file${url.suffix}")
	public String file(HttpServletRequest request, Model model,
			@RequestParam(value = "id", required = false , defaultValue="0") int id){
		if(!haveSuperAdminAuth()){
			return error(model, "无权使用");
		}

		InnerDownFile file;
		if(id > 0){
			//修改
			file = sqlService.findById(InnerDownFile.class, id);
			if(file == null){
				return error(model, "修改的文件记录不存在");
			}
		}else{
			//新增加
			file = new InnerDownFile();
		}
		
		//日志
		AliyunLog.addActionLog((file.getId() != null && file.getId() > 0)? file.getId():0, ((file.getId() != null && file.getId() > 0) ? "修改":"新增")+"文件记录-打开修改页面-plugin-innerDown", file.getName());
				
		
		//可上传的后缀列表
		model.addAttribute("ossFileUploadImageSuffixList", Global.ossFileUploadImageSuffixList);
		//可上传的文件最大大小(KB)
		model.addAttribute("maxFileSizeKB", AttachmentFile.getMaxFileSizeKB());
		model.addAttribute("file", file);
		return "plugin/innerDown/admin/file/file";
	}
	

	/**
	 * 文件新增或者修改后的保存 (plugin_innerdown_file 数据表的信息保存，而非单纯一个文件)
	 */
	@RequestMapping(value="fileSave${url.suffix}", method = RequestMethod.POST)
	@ResponseBody
	public BaseVO fileSave(HttpServletRequest request, InnerDownFile fileInput){
		if(!haveSuperAdminAuth()){
			return error("无权使用");
		}
		
		InnerDownFile file;
		if(fileInput.getId() != null && fileInput.getId() > 0){
			//修改
			file = sqlService.findById(InnerDownFile.class, fileInput.getId());
		}else{
			//新增
			file = new InnerDownFile();
			file.setAddtime(DateUtil.timeForUnix10());
			file.setIsdelete(InnerDownFile.ISDELETE_NORMAL);
			file.setUserid(getUserId());
			file.setBranchid(0);	//部门为0则是可用于所有部门
		}
		
		file.setName(filter(fileInput.getName()));
		file.setSize(fileInput.getSize());
		file.setSuffix(filter(fileInput.getSuffix()));
		file.setUrl(StringUtil.filterXss(fileInput.getUrl()));
		sqlService.save(file);
		
		//日志
		AliyunLog.addActionLog(file.getId(), ((fileInput.getId() != null && fileInput.getId() > 0) ? "修改":"新增")+"文件记录保存完成-plugin-innerDown", file.getName());
		
		return success();
	}
	

	/**
	 * 文件信息删除
	 */
	@RequestMapping(value="deleteFile${url.suffix}", method = RequestMethod.POST)
	@ResponseBody
	public BaseVO deleteFile(HttpServletRequest request, 
			@RequestParam(value = "id", required = false , defaultValue="0") int id){
		if(!haveSuperAdminAuth()){
			return error("无权使用");
		}
		
		if(id == 0){
			return error("请传入要删除的文件id");
		}
		
		InnerDownFile file = sqlService.findById(InnerDownFile.class, id);
		if(file == null){
			return error("要删除的文件不存在");
		}
		
		sqlService.delete(file);
		//日志
		AliyunLog.addActionLog(file.getId(), "删除文件-plugin-innerDown", file.getName());
		
		//删除存储的附件。因为数据库记录的是绝对路径，所以要进行截取
		if(file.getUrl().indexOf(AttachmentFile.netUrl()) > -1){
			String relativePath = file.getUrl().substring(file.getUrl().indexOf(AttachmentFile.netUrl())+AttachmentFile.netUrl().length(), file.getUrl().length());
			if(relativePath.length() > 2){
				AttachmentFile.deleteObject(relativePath);
			}
		}
		
		return success();
	}
	
}
